package com.jblog.controller.web;

import static com.jblog.Constants.System.ACCOUNT_ID;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.jblog.common.web.CookieUtils;
import com.jblog.core.model.account.Account;
import com.jblog.core.model.site.Site;
import com.jblog.core.service.facde.AccountFacade;
import com.jblog.core.service.facde.SiteFacade;

public class FrontContextInterceptor extends HandlerInterceptorAdapter {

    @Autowired private SiteFacade isite;
    @Autowired private AccountFacade iAccount;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
            Object handler) throws ServletException {

        Site site = isite.findSite();
        if (null == site) {
            throw new RuntimeException("no site record in database");
        } else {
            String server = request.getServerName();
            if (!server.equalsIgnoreCase(site.getDomain())) {
                throw new RuntimeException("site: " + server + ", not find in database");
            }
        }
        SiteUtils.setSite(request, site);
        
        Account account = null;
        Long accountId = (Long)request.getSession().getAttribute(ACCOUNT_ID);
        account = findAccountById(accountId);
        if (null == account) {
            Cookie cookie = CookieUtils.readCookie(request, ACCOUNT_ID);
            if (null != cookie && StringUtils.isNotBlank(cookie.getValue())) {
                accountId = new Long(cookie.getValue());
                account = findAccountById(accountId);
            }
        }
        if (null != account) {
            SiteUtils.setAccount(request, account);
        }

        return true;
    }
    
    private Account findAccountById(Long id) {
        if (null != id) {
            return iAccount.findAccountById(id);
        }
        return null;
    }

}
